package com.TomcatServlet;

import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Logger;

/**
 * Created by 41579 on 2017/7/12.
 */
public class ServletSimulation {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(8080);
        while(true){
            Socket socket = ss.accept();
            System.out.println("接受到请求k："+socket.getRemoteSocketAddress());
            BufferedInputStream bis =  new BufferedInputStream(socket.getInputStream());
            OutputStream outputStream  = socket.getOutputStream();

            String header="HTTP/1.1 200 OK\r\n";
            header +="Content-Type: text/html\r\n\r\n";
            String content = "<a href='#'>123123</a>";
            /**
             * 第一次在这里没加等待时间，直接被坑，导致浏览器发出请求都没有inputstream,因为inputstrem还没来
             */
//            try {
//                Thread.sleep(5000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
            /**
             * 注意这里不能用 bis.available()，因为这个是后inputstream可能还没都进来！导致 bis.available()为0后续的read操作无法读取
             */
            byte[] requestByte = new byte[1024];
            if(bis.read(requestByte)>0){
                System.out.println(new String(requestByte));
                outputStream.write(header.getBytes());
                outputStream.write(content.getBytes());
                outputStream.flush();
                outputStream.close();
            }
            System.out.println("读取完成，准备下一次读取");
        }
    }
}
